package haxeframe.ui;

import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.Lib;

class Input
{
	public static var keysDown:Array<Bool> = new Array<Bool>();
	public static var keysPressed:Array<Bool> = new Array<Bool>();

	private static var stage:Dynamic;

	public static function init():Void
	{
		if(stage != null) kill();
		stage = Lib.current.stage;
		stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyboard, false, 1);
		stage.addEventListener(KeyboardEvent.KEY_UP, handleKeyboard, false, 1);
		stage.addEventListener(Event.ENTER_FRAME, update, false, -1);
	}

	public static function kill():Void
	{
		stage.removeEventListener(KeyboardEvent.KEY_DOWN, handleKeyboard, false, 1);
		stage.removeEventListener(KeyboardEvent.KEY_UP, handleKeyboard, false, 1);
		stage.removeEventListener(Event.ENTER_FRAME, update, false, -1);
	}

	private static function handleKeyboard(event:KeyboardEvent):Void
	{
		switch(event.type){

			case KeyboardEvent.KEY_DOWN :
				keysDown[event.keyCode] = keysPressed[event.keyCode] = true;

			case KeyboardEvent.KEY_UP :
				keysDown[event.keyCode] = keysPressed[event.keyCode] = false;

		}
	}

	private static function update(event:Event=null):Void
	{
		keysPressed = new Array<Bool>();
		keysPressed[256] = false;
	}
}